// 用户相关的本地存储操作

// 新增：积分系统相关数据结构
export const POINT_SYSTEM = {
  STAR_COINS_PER_DAY: 2, // 每日签到获得星币
  STAR_COINS_DOWNLOAD_COST: 1, // 下载资源消耗星币
  UPLOAD_RATIO_PER_STAR_COIN: 1024, // 1星币=1GB上传量
  UPLOAD_RATIO_PER_MAGIC: 512, // 1魔力值=512MB上传量

  // 用户等级称号 (基于点赞总数)
  USER_TITLES: [
    { minLikes: 0, maxLikes: 9, title: '新手', level: 'V1', color: '#8c8c8c' },
    { minLikes: 10, maxLikes: 49, title: '资源爱好者', level: 'V2', color: '#52c41a' },
    { minLikes: 50, maxLikes: 199, title: '资源达人', level: 'V3', color: '#1890ff' },
    { minLikes: 200, maxLikes: 499, title: '资源专家', level: 'V4', color: '#722ed1' },
    { minLikes: 500, maxLikes: 999, title: '资源发掘者', level: 'V5', color: '#eb2f96' },
    { minLikes: 1000, maxLikes: Infinity, title: '资源大师', level: 'V6', color: '#fa8c16' }
  ]
};

// 初始化用户积分数据
export const initUserPoints = (username) => {
  const pointsStr = localStorage.getItem('starrypt_user_points');
  let allPoints = pointsStr ? JSON.parse(pointsStr) : {};

  if (!allPoints[username]) {
    allPoints[username] = {
      starCoins: 10, // 初始星币
      magicValue: 0, // 魔力值
      totalLikes: 0, // 总点赞数
      dailySignIn: null, // 最后签到日期
      downloadHistory: [], // 下载历史
      uploadContribution: 0 // 上传贡献度
    };
    localStorage.setItem('starrypt_user_points', JSON.stringify(allPoints));
  }

  return allPoints[username];
};

// 获取用户积分信息
export const getUserPoints = (username) => {
  const pointsStr = localStorage.getItem('starrypt_user_points');
  const allPoints = pointsStr ? JSON.parse(pointsStr) : {};
  return allPoints[username] || initUserPoints(username);
};

// 更新用户积分信息
export const updateUserPoints = (username, updates) => {
  const pointsStr = localStorage.getItem('starrypt_user_points');
  let allPoints = pointsStr ? JSON.parse(pointsStr) : {};

  if (!allPoints[username]) {
    allPoints[username] = initUserPoints(username);
  }

  allPoints[username] = { ...allPoints[username], ...updates };
  localStorage.setItem('starrypt_user_points', JSON.stringify(allPoints));
  return allPoints[username];
};

// 每日签到
export const dailySignIn = (username) => {
  const today = new Date().toDateString();
  const userPoints = getUserPoints(username);

  if (userPoints.dailySignIn === today) {
    return { success: false, message: '今日已签到' };
  }

  const newPoints = updateUserPoints(username, {
    starCoins: userPoints.starCoins + POINT_SYSTEM.STAR_COINS_PER_DAY,
    dailySignIn: today
  });

  return {
    success: true,
    message: `签到成功！获得${POINT_SYSTEM.STAR_COINS_PER_DAY}星币`,
    starCoins: newPoints.starCoins
  };
};

// 计算用户称号
export const calculateUserTitle = (totalLikes) => {
  return POINT_SYSTEM.USER_TITLES.find(title =>
    totalLikes >= title.minLikes && totalLikes <= title.maxLikes
  ) || POINT_SYSTEM.USER_TITLES[0];
};

// 星币兑换上传量
export const exchangeStarCoinsForUpload = (username, starCoins) => {
  const userPoints = getUserPoints(username);

  if (userPoints.starCoins < starCoins) {
    return { success: false, message: '星币不足' };
  }

  const uploadAmount = starCoins * POINT_SYSTEM.UPLOAD_RATIO_PER_STAR_COIN; // MB

  updateUserPoints(username, {
    starCoins: userPoints.starCoins - starCoins
  });

  // 更新用户上传量
  const user = getUser();
  if (user && user.username === username) {
    user.uploadCount = (user.uploadCount || 0) + uploadAmount / 1024; // 转为GB
    saveUser(user);
  }

  return {
    success: true,
    message: `成功兑换${uploadAmount / 1024}GB上传量`,
    uploadAmount: uploadAmount / 1024
  };
};

// 魔力值兑换上传量
export const exchangeMagicForUpload = (username, magicValue) => {
  const userPoints = getUserPoints(username);

  if (userPoints.magicValue < magicValue) {
    return { success: false, message: '魔力值不足' };
  }

  const uploadAmount = magicValue * POINT_SYSTEM.UPLOAD_RATIO_PER_MAGIC; // MB

  updateUserPoints(username, {
    magicValue: userPoints.magicValue - magicValue
  });

  // 更新用户上传量
  const user = getUser();
  if (user && user.username === username) {
    user.uploadCount = (user.uploadCount || 0) + uploadAmount / 1024; // 转为GB
    saveUser(user);
  }

  return {
    success: true,
    message: `成功兑换${uploadAmount / 1024}GB上传量`,
    uploadAmount: uploadAmount / 1024
  };
};

// 保存用户信息
export const saveUser = (user) => {
  localStorage.setItem('starrypt_user', JSON.stringify(user));
};

// 获取用户信息
export const getUser = () => {
  const userStr = localStorage.getItem('starrypt_user');
  return userStr ? JSON.parse(userStr) : null;
};

// 删除用户信息（登出）
export const removeUser = () => {
  localStorage.removeItem('starrypt_user');
};

// 检查用户是否已登录
export const isLoggedIn = () => {
  return !!localStorage.getItem('starrypt_user');
};

// 初始化邀请码数据
export const initInviteCodes = () => {
  const inviteCodesStr = localStorage.getItem('starrypt_invite_codes');
  if (!inviteCodesStr) {
    // 初始有效邀请码列表
    const initialInviteCodes = [
      { code: 'INVITE001', used: false, createdBy: 'admin', creatorEmail: 'admin@pku.edu.cn', emailDomain: 'pku.edu.cn', createdAt: '2023-01-01T00:00:00.000Z' },
      { code: 'INVITE002', used: false, createdBy: 'admin', creatorEmail: 'admin@pku.edu.cn', emailDomain: 'pku.edu.cn', createdAt: '2023-01-01T00:00:00.000Z' },
      { code: 'INVITE003', used: false, createdBy: 'admin', creatorEmail: 'admin@pku.edu.cn', emailDomain: 'pku.edu.cn', createdAt: '2023-01-01T00:00:00.000Z' },
      { code: 'INVITE004', used: false, createdBy: 'admin', creatorEmail: 'admin@pku.edu.cn', emailDomain: 'pku.edu.cn', createdAt: '2023-01-01T00:00:00.000Z' },
      { code: 'INVITE005', used: false, createdBy: 'admin', creatorEmail: 'admin@pku.edu.cn', emailDomain: 'pku.edu.cn', createdAt: '2023-01-01T00:00:00.000Z' },
    ];
    localStorage.setItem('starrypt_invite_codes', JSON.stringify(initialInviteCodes));
    return initialInviteCodes;
  }
  return JSON.parse(inviteCodesStr);
};

// 生成邀请码
export const generateInviteCode = () => {
  // 获取当前用户
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  // 检查用户邮箱是否存在
  if (!user.email) {
    return { success: false, message: '用户邮箱信息缺失，请重新登录获取完整用户信息' };
  }

  // 提取用户邮箱的域名部分
  const emailParts = user.email.split('@');
  const domain = emailParts.length > 1 ? emailParts[1] : null;

  if (!domain) {
    return { success: false, message: '无效的邮箱格式' };
  }

  // 生成随机15位字符邀请码（参考后端实现）
  const generateRandomCode = () => {
    return Math.random().toString(36).substring(2, 15) +
      Math.random().toString(36).substring(2, 8);
  };

  const code = generateRandomCode().substring(0, 15).toUpperCase();

  // 创建新的邀请码对象
  const newInviteCode = {
    code: code,
    used: false,
    createdBy: user.username,
    creatorId: user.userId || null,
    creatorEmail: user.email,
    emailDomain: domain,
    createdAt: new Date().toISOString(),
    usedBy: null,
    usedAt: null
  };

  return { success: true, inviteCode: newInviteCode };
};

// 本地存储邀请码（仅在API不可用时使用）
export const saveInviteCode = (inviteCode) => {
  if (!inviteCode) {
    return { success: false, message: '邀请码对象无效' };
  }

  // 获取邀请码列表
  const inviteCodes = JSON.parse(localStorage.getItem('starrypt_invite_codes')) || initInviteCodes();

  // 添加到邀请码列表
  inviteCodes.push(inviteCode);
  localStorage.setItem('starrypt_invite_codes', JSON.stringify(inviteCodes));

  return { success: true };
};

// 获取用户生成的邀请码
export const getUserInviteCodes = () => {
  const user = getUser();
  if (!user) {
    return [];
  }

  const inviteCodes = JSON.parse(localStorage.getItem('starrypt_invite_codes')) || initInviteCodes();
  return inviteCodes.filter(code => code.createdBy === user.username);
};

// 删除邀请码
export const deleteInviteCode = (code) => {
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  // 获取邀请码列表
  const inviteCodes = JSON.parse(localStorage.getItem('starrypt_invite_codes')) || initInviteCodes();

  // 查找邀请码
  const targetCode = inviteCodes.find(c => c.code === code);

  if (!targetCode) {
    return { success: false, message: '邀请码不存在' };
  }

  // 检查邀请码是否属于当前用户
  if (targetCode.createdBy !== user.username) {
    return { success: false, message: '无权删除该邀请码' };
  }

  // 检查邀请码是否已被使用
  if (targetCode.used) {
    return { success: false, message: '已被使用的邀请码无法删除' };
  }

  // 删除邀请码
  const updatedCodes = inviteCodes.filter(c => c.code !== code);
  localStorage.setItem('starrypt_invite_codes', JSON.stringify(updatedCodes));

  return { success: true, message: '邀请码删除成功' };
};

// 验证邀请码，返回更详细的验证结果
export const validateInviteCodeDetail = (inviteCode, email) => {
  if (!inviteCode || !email) {
    return { valid: false, errorType: 'missing_info', message: '邀请码或邮箱缺失' };
  }

  const inviteCodes = JSON.parse(localStorage.getItem('starrypt_invite_codes')) || initInviteCodes();
  const foundCode = inviteCodes.find(code => code.code === inviteCode);

  if (!foundCode) {
    return { valid: false, errorType: 'not_found', message: '邀请码不存在' };
  }

  if (foundCode.used) {
    return { valid: false, errorType: 'used', message: '邀请码已被使用' };
  }

  // 提取邮箱的域名部分
  const emailParts = email.split('@');
  const domain = emailParts.length > 1 ? emailParts[1] : null;

  // 检查邮箱域名是否与邀请码的创建者域名相同
  if (domain !== foundCode.emailDomain) {
    console.log('邮箱域名与邀请者不匹配。此邀请码仅限 @${foundCode.emailDomain} 邮箱使用');
    return {
      valid: false,
      errorType: 'domain_mismatch',
      message: `邮箱域名与邀请者不匹配。此邀请码仅限 @${foundCode.emailDomain} 邮箱使用`,
      inviterDomain: foundCode.emailDomain,
      userDomain: domain
    };
  }

  return {
    valid: true,
    inviteCode: foundCode
  };
};

// 原始的验证函数，保持不变以兼容现有代码
export const validateInviteCode = (inviteCode, email) => {
  if (!inviteCode || !email) return false;

  const inviteCodes = JSON.parse(localStorage.getItem('starrypt_invite_codes')) || initInviteCodes();
  const foundCode = inviteCodes.find(code => code.code === inviteCode && !code.used);

  if (!foundCode) {
    return false; // 邀请码不存在或已被使用
  }

  // 提取邮箱的域名部分
  const emailParts = email.split('@');
  const domain = emailParts.length > 1 ? emailParts[1] : null;

  // 检查邮箱域名是否与邀请码的创建者域名相同
  if (domain !== foundCode.emailDomain) {
    return false; // 邮箱域名不匹配
  }

  // 邀请码有效且域名匹配，标记为已使用
  const updatedCodes = inviteCodes.map(code =>
    code.code === inviteCode ? { ...code, used: true, usedBy: email, usedAt: new Date().toISOString() } : code
  );
  localStorage.setItem('starrypt_invite_codes', JSON.stringify(updatedCodes));
  return true;
};

// 注册用户
export const registerUser = (username, password, email, inviteCode = null) => {
  // 获取当前注册的所有用户
  const usersStr = localStorage.getItem('starrypt_users');
  const users = usersStr ? JSON.parse(usersStr) : [];

  // 检查用户名是否已存在
  const existingUser = users.find(user => user.username === username);
  if (existingUser) {
    return { success: false, message: '用户名已存在' };
  }

  // 验证邮箱必须以.edu.cn结尾
  if (!email.toLowerCase().endsWith('.edu.cn')) {
    return { success: false, message: '必须使用以.edu.cn结尾的教育邮箱' };
  }

  // 如果提供了邀请码，验证邀请码是否有效
  if (inviteCode) {
    const isValidInvite = validateInviteCode(inviteCode, email);
    if (!isValidInvite) {
      return { success: false, message: '邀请码无效、已被使用或邮箱域名与邀请者不匹配' };
    }
  }

  // 添加新用户
  const newUser = {
    username,
    password, // 注意：实际应用中应该对密码进行加密
    email,
    registerDate: new Date().toISOString(),
    uploadCount: 0,
    downloadCount: 0,
    ratio: 1.0,
    inviteCode: inviteCode, // 记录用户是通过哪个邀请码注册的
    registerType: inviteCode ? 'invite' : 'normal' // 记录注册类型
  };

  users.push(newUser);
  localStorage.setItem('starrypt_users', JSON.stringify(users));

  // 不返回密码
  const { password: _, ...userWithoutPassword } = newUser;
  return { success: true, user: userWithoutPassword };
};

// 登录
export const loginUser = (username, password) => {
  const usersStr = localStorage.getItem('starrypt_users');
  const users = usersStr ? JSON.parse(usersStr) : [];

  const user = users.find(u => u.username === username && u.password === password);

  if (user) {
    // 不返回密码
    const { password: _, ...userWithoutPassword } = user;
    return { success: true, user: userWithoutPassword };
  } else {
    return { success: false, message: '用户名或密码错误' };
  }
};

// =========== 种子相关操作 ===========

// 初始化种子数据
export const initTorrents = () => {
  const torrentsStr = localStorage.getItem('starrypt_torrents');
  if (!torrentsStr) {
    const initialTorrents = [
      {
        id: 1,
        title: '星际穿越 4K蓝光',
        description: '克里斯托弗·诺兰导演的科幻杰作，4K超高清蓝光版本，音画质量极佳。',
        size: '45.6 GB',
        category: '电影',
        tags: ['科幻', '冒险', '诺兰'],
        seeders: 125,
        leechers: 34,
        uploadDate: '2023-05-15',
        uploader: 'admin',
        downloads: 567,
        coverImage: 'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2206088801.jpg',
        files: [
          { name: 'Interstellar.2014.4K.BluRay.mkv', size: '42.5 GB' },
          { name: 'Subtitles', size: '15 MB' },
          { name: 'Extras', size: '3.1 GB' }
        ],

      },
      {
        id: 2,
        title: '流浪地球2 4K HDR',
        description: '《流浪地球2》是2023年上映的中国科幻电影，讲述了人类为了逃离太阳即将膨胀为红巨星的灾难，推行"流浪地球计划"的故事。',
        size: '58.2 GB',
        category: '电影',
        tags: ['科幻', '灾难', '中国电影'],
        seeders: 89,
        leechers: 45,
        uploadDate: '2023-08-20',
        uploader: 'scifi_master',
        downloads: 321,
        coverImage: 'https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2885955777.jpg',
        files: [
          { name: 'The.Wandering.Earth.2.2023.4K.HDR.mkv', size: '56.7 GB' },
          { name: 'Subtitles', size: '24 MB' },
          { name: 'Info.txt', size: '5 KB' }
        ],

      },
      {
        id: 3,
        title: '三体 全集',
        description: '改编自刘慈欣科幻小说《三体》的电视剧全集，高清晰度，包含全部30集。',
        size: '24.7 GB',
        category: '电视剧',
        tags: ['科幻', '刘慈欣', '中国科幻'],
        seeders: 134,
        leechers: 23,
        uploadDate: '2023-09-10',
        uploader: 'book_lover',
        downloads: 452,
        coverImage: 'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2886492019.jpg',
        files: [
          { name: 'Three.Body.S01.1080p', size: '24.5 GB' },
          { name: 'Extras', size: '200 MB' }
        ],

      },
      {
        id: 4,
        title: '太空漫游 精选集',
        description: '关于太空探索的纪录片合集，包含多部经典纪录片，高清1080p质量。',
        size: '16.9 GB',
        category: '纪录片',
        tags: ['太空', '探索', '科学'],
        seeders: 56,
        leechers: 12,
        uploadDate: '2023-10-01',
        uploader: 'space_explorer',
        downloads: 187,
        coverImage: 'https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2549504556.jpg',
        files: [
          { name: 'Space.Exploration.Collection.1080p', size: '16.5 GB' },
          { name: 'Booklet.pdf', size: '45 MB' },
          { name: 'Info.txt', size: '2 KB' }
        ],

      },
      {
        id: 5,
        title: '暗物质 全季',
        description: '科幻电视剧《暗物质》全季高清资源，基于Blake Crouch的小说改编，探索多重宇宙的科幻剧。',
        size: '35.8 GB',
        category: '电视剧',
        tags: ['科幻', '悬疑', '多重宇宙'],
        seeders: 78,
        leechers: 22,
        uploadDate: '2023-11-05',
        uploader: 'series_collector',
        downloads: 245,
        coverImage: 'https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2887666968.jpg',
        files: [
          { name: 'Dark.Matter.Complete.1080p', size: '35.5 GB' },
          { name: 'Subtitles', size: '30 MB' },
          { name: 'Artwork', size: '250 MB' }
        ],

      }
    ];

    localStorage.setItem('starrypt_torrents', JSON.stringify(initialTorrents));
    return initialTorrents;
  }

  return JSON.parse(torrentsStr);
};

// 获取所有种子
export const getAllTorrents = () => {
  let torrents = localStorage.getItem('starrypt_torrents');
  if (!torrents) {
    torrents = initTorrents();
  } else {
    torrents = JSON.parse(torrents);
  }

  return torrents;
};

// 根据ID获取种子
export const getTorrentById = (id) => {
  const torrents = getAllTorrents();
  return torrents.find(torrent => torrent.id === parseInt(id, 10)) || null;
};

// 根据分类获取种子
export const getTorrentsByCategory = (category) => {
  const torrents = getAllTorrents();
  return category ? torrents.filter(torrent => torrent.category === category) : torrents;
};

// 根据标签获取种子
export const getTorrentsByTag = (tag) => {
  const torrents = getAllTorrents();
  return tag ? torrents.filter(torrent => torrent.tags.includes(tag)) : torrents;
};

// 搜索种子
export const searchTorrents = (query) => {
  const torrents = getAllTorrents();
  if (!query) return torrents;

  const lowerQuery = query.toLowerCase();
  return torrents.filter(torrent =>
    torrent.title.toLowerCase().includes(lowerQuery) ||
    torrent.description.toLowerCase().includes(lowerQuery) ||
    torrent.tags.some(tag => tag.toLowerCase().includes(lowerQuery))
  );
};

// 计算种子质量分数
export const calculateQualityScore = (torrentData) => {
  let score = 0;

  // 基础分数
  score += 10;

  // 根据分类给分
  const categoryBonus = {
    '电影': 15,
    '电视剧': 12,
    '纪录片': 18,
    '动漫': 10,
    '音乐': 8,
    '图书': 8,
    '软件': 12,
    '游戏': 10
  };
  score += categoryBonus[torrentData.category] || 5;

  // 根据标签给分
  const highQualityTags = ['4K', 'HDR', 'IMAX', '蓝光', '原盘', 'REMUX'];
  const qualityTagCount = (torrentData.tags || []).filter(tag =>
    highQualityTags.some(hqTag => tag.includes(hqTag))
  ).length;
  score += qualityTagCount * 5;

  // 根据文件大小给分（大文件通常质量更高）
  if (torrentData.size) {
    const sizeMatch = torrentData.size.match(/(\d+(?:\.\d+)?)\s*(GB|MB)/i);
    if (sizeMatch) {
      const size = parseFloat(sizeMatch[1]);
      const unit = sizeMatch[2].toUpperCase();
      const sizeInGB = unit === 'GB' ? size : size / 1024;

      if (sizeInGB > 20) score += 15; // 超大文件
      else if (sizeInGB > 5) score += 10; // 大文件
      else if (sizeInGB > 1) score += 5; // 中等文件
    }
  }

  return Math.min(score, 100); // 最大100分
};

// 计算上传贡献值（用于魔力值）
export const calculateUploadContribution = (torrentData) => {
  const qualityScore = calculateQualityScore(torrentData);

  // 基础贡献值 = 质量分数 / 2
  let contribution = Math.floor(qualityScore / 2);

  // 稀有资源额外奖励
  const rareTags = ['收藏版', '限定版', '导演剪辑版', '未删减', '修复版'];
  const rareTagCount = (torrentData.tags || []).filter(tag =>
    rareTags.some(rareTag => tag.includes(rareTag))
  ).length;
  contribution += rareTagCount * 5;

  return Math.max(contribution, 5); // 最少5点贡献值
};

// 添加新种子
export const addTorrent = (torrentData) => {
  const torrents = getAllTorrents();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  // 计算质量相关分数
  const qualityScore = calculateQualityScore(torrentData);
  const uploadContribution = calculateUploadContribution(torrentData);

  const newTorrent = {
    id: Date.now(),
    ...torrentData,
    uploadDate: new Date().toISOString().split('T')[0],
    uploader: user.username,
    seeders: 1,
    leechers: 0,
    downloads: 0,
    likes: 0, // 新增点赞数
    qualityScore: qualityScore, // 新增质量分数
    uploadContribution: uploadContribution // 新增上传贡献值
  };

  torrents.push(newTorrent);
  localStorage.setItem('starrypt_torrents', JSON.stringify(torrents));

  // 更新用户上传计数
  updateUserUploadStats(user.username);

  // 增加用户魔力值（基于种子质量）
  const userPoints = getUserPoints(user.username);
  updateUserPoints(user.username, {
    magicValue: userPoints.magicValue + uploadContribution,
    uploadContribution: userPoints.uploadContribution + uploadContribution
  });

  return { success: true, torrent: newTorrent };
};



// 下载种子
export const downloadTorrent = (torrentId) => {
  const torrents = getAllTorrents();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const torrentIndex = torrents.findIndex(t => t.id === parseInt(torrentId, 10));

  if (torrentIndex === -1) {
    return { success: false, message: '种子不存在' };
  }

  const torrent = torrents[torrentIndex];

  // 检查是否需要消耗星币（如果种子设置了星币成本）
  const starCoinCost = torrent.starCoinCost || POINT_SYSTEM.STAR_COINS_DOWNLOAD_COST;
  const userPoints = getUserPoints(user.username);

  if (userPoints.starCoins < starCoinCost) {
    return { success: false, message: `星币不足，需要${starCoinCost}星币` };
  }

  // 扣除星币
  updateUserPoints(user.username, {
    starCoins: userPoints.starCoins - starCoinCost,
    downloadHistory: [...userPoints.downloadHistory, {
      torrentId: torrent.id,
      title: torrent.title,
      downloadTime: new Date().toISOString(),
      starCoinCost: starCoinCost
    }]
  });

  // 增加下载计数
  torrents[torrentIndex].downloads += 1;
  localStorage.setItem('starrypt_torrents', JSON.stringify(torrents));

  // 更新用户下载统计
  updateUserDownloadStats(user.username);

  // 给上传者增加一定魔力值奖励（鼓励分享）
  if (torrent.uploader && torrent.uploader !== user.username) {
    const uploaderPoints = getUserPoints(torrent.uploader);
    updateUserPoints(torrent.uploader, {
      magicValue: uploaderPoints.magicValue + 1
    });
  }

  return {
    success: true,
    message: `下载成功，消耗${starCoinCost}星币`,
    torrentFileUrl: `data:application/x-bittorrent;base64,${btoa(`d8:announce31:http://tracker.starrypt.com:6969/10:created by13:Starrypt PT13:creation datei${Math.floor(Date.now() / 1000)}e4:infod5:filesld6:lengthi${parseInt(torrents[torrentIndex].size)}e4:pathl${torrents[torrentIndex].title}eee4:name${torrents[torrentIndex].title.length}:${torrents[torrentIndex].title}12:piece lengthi16384e6:pieces20:aaaabbbbccccddddeeeeee`)}`,
    torrentName: `${torrents[torrentIndex].title.replace(/\s+/g, '.').toLowerCase()}.torrent`
  };
};

// 更新用户上传统计
const updateUserUploadStats = (username) => {
  const usersStr = localStorage.getItem('starrypt_users');
  if (!usersStr) return;

  const users = JSON.parse(usersStr);
  const userIndex = users.findIndex(u => u.username === username);

  if (userIndex === -1) return;

  // 简单起见，每次上传增加10GB
  users[userIndex].uploadCount += 10;

  // 重新计算分享率
  if (users[userIndex].downloadCount > 0) {
    users[userIndex].ratio = users[userIndex].uploadCount / users[userIndex].downloadCount;
  } else {
    users[userIndex].ratio = users[userIndex].uploadCount > 0 ? 999.99 : 1.0;
  }

  localStorage.setItem('starrypt_users', JSON.stringify(users));

  // 如果当前用户正在登录，也更新当前登录用户信息
  const currentUser = getUser();
  if (currentUser && currentUser.username === username) {
    const { password, ...userInfo } = users[userIndex];
    saveUser(userInfo);
  }
};

// 更新用户下载统计
const updateUserDownloadStats = (username) => {
  const usersStr = localStorage.getItem('starrypt_users');
  if (!usersStr) return;

  const users = JSON.parse(usersStr);
  const userIndex = users.findIndex(u => u.username === username);

  if (userIndex === -1) return;

  // 简单起见，每次下载增加5GB
  users[userIndex].downloadCount += 5;

  // 重新计算分享率
  if (users[userIndex].downloadCount > 0) {
    users[userIndex].ratio = users[userIndex].uploadCount / users[userIndex].downloadCount;
  } else {
    users[userIndex].ratio = users[userIndex].uploadCount > 0 ? 999.99 : 1.0;
  }

  localStorage.setItem('starrypt_users', JSON.stringify(users));

  // 如果当前用户正在登录，也更新当前登录用户信息
  const currentUser = getUser();
  if (currentUser && currentUser.username === username) {
    const { password, ...userInfo } = users[userIndex];
    saveUser(userInfo);
  }
};

// 点赞种子
export const likeTorrent = (torrentId) => {
  const torrents = getAllTorrents();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const torrentIndex = torrents.findIndex(t => t.id === parseInt(torrentId, 10));

  if (torrentIndex === -1) {
    return { success: false, message: '种子不存在' };
  }

  const torrent = torrents[torrentIndex];

  // 检查用户是否已经点赞过
  const likedTorrentsStr = localStorage.getItem('starrypt_user_likes');
  let likedTorrents = likedTorrentsStr ? JSON.parse(likedTorrentsStr) : {};

  if (!likedTorrents[user.username]) {
    likedTorrents[user.username] = [];
  }

  const hasLiked = likedTorrents[user.username].includes(torrentId);

  if (hasLiked) {
    // 取消点赞
    likedTorrents[user.username] = likedTorrents[user.username].filter(id => id !== torrentId);
    torrents[torrentIndex].likes = Math.max(0, torrents[torrentIndex].likes - 1);
  } else {
    // 添加点赞
    likedTorrents[user.username].push(torrentId);
    torrents[torrentIndex].likes = (torrents[torrentIndex].likes || 0) + 1;

    // 给上传者增加总点赞数
    if (torrent.uploader && torrent.uploader !== user.username) {
      const uploaderPoints = getUserPoints(torrent.uploader);
      updateUserPoints(torrent.uploader, {
        totalLikes: uploaderPoints.totalLikes + 1
      });
    }
  }

  localStorage.setItem('starrypt_user_likes', JSON.stringify(likedTorrents));
  localStorage.setItem('starrypt_torrents', JSON.stringify(torrents));

  return {
    success: true,
    message: hasLiked ? '取消点赞成功' : '点赞成功',
    liked: !hasLiked,
    likes: torrents[torrentIndex].likes
  };
};

// 检查用户是否点赞了某个种子
export const hasUserLikedTorrent = (torrentId) => {
  const user = getUser();
  if (!user) return false;

  const likedTorrentsStr = localStorage.getItem('starrypt_user_likes');
  const likedTorrents = likedTorrentsStr ? JSON.parse(likedTorrentsStr) : {};

  return likedTorrents[user.username] && likedTorrents[user.username].includes(torrentId);
};

// 获取用户上传的种子
export const getUserTorrents = (username) => {
  const torrents = getAllTorrents();
  return torrents.filter(torrent => torrent.uploader === username);
};

// 初始化数据
export const initData = () => {
  // 初始化管理员用户
  const usersStr = localStorage.getItem('starrypt_users');
  if (!usersStr) {
    const initialUsers = [
      {
        username: 'admin',
        password: 'admin123',
        email: 'admin@pku.edu.cn',
        registerDate: '2023-01-01T00:00:00.000Z',
        uploadCount: 100,
        downloadCount: 20,
        ratio: 5.0,
        registerType: 'normal'
      },
      {
        username: 'test',
        password: 'test123',
        email: 'test@pku.edu.cn',
        registerDate: new Date().toISOString(),
        uploadCount: 5,
        downloadCount: 10,
        ratio: 0.5,
        registerType: 'normal'
      }
    ];
    localStorage.setItem('starrypt_users', JSON.stringify(initialUsers));
  }

  // 初始化种子数据
  initTorrents();

  // 初始化邀请码
  initInviteCodes();

  // 初始化新功能数据
  initTopics();
  initTopicPosts();
  initCategories();
  initBroadcasts();

  // 初始化用户积分
  initUserPoints('admin');
  initUserPoints('test');
};

// =========== 新增：话题管理系统 ===========

// 初始化话题(群组)数据
export const initTopics = () => {
  const topicsStr = localStorage.getItem('starrypt_topics');
  if (!topicsStr) {
    const initialTopics = [
      {
        id: 1,
        name: '电影分享交流',
        description: '分享和讨论各类电影资源，交流观影心得',
        creator: 'admin',
        creatorId: 1,
        category: '资源分享',
        tags: ['电影', '分享'],
        createTime: '2023-01-01T00:00:00.000Z',
        memberCount: 156,
        postCount: 89,
        isPublic: true,
        cover: '/api/placeholder/400/200',
        rules: ['禁止发布盗版内容', '保持文明讨论', '相关内容优先']
      },
      {
        id: 2,
        name: '求种互助群',
        description: '帮助大家寻找各种稀有资源，互助共享',
        creator: 'helper_user',
        creatorId: 2,
        category: '求助互助',
        tags: ['求种', '互助'],
        createTime: '2023-02-01T00:00:00.000Z',
        memberCount: 234,
        postCount: 145,
        isPublic: true,
        cover: '/api/placeholder/400/200',
        rules: ['提供详细资源信息', '感谢分享者', '积极回馈社区']
      },
      {
        id: 3,
        name: '技术讨论区',
        description: 'PT技术讨论，下载工具使用心得分享',
        creator: 'tech_expert',
        creatorId: 3,
        category: '技术交流',
        tags: ['技术', 'PT'],
        createTime: '2023-03-01T00:00:00.000Z',
        memberCount: 78,
        postCount: 56,
        isPublic: true,
        cover: '/api/placeholder/400/200',
        rules: ['技术内容为主', '禁止发布破解内容', '尊重知识产权']
      }
    ];
    localStorage.setItem('starrypt_topics', JSON.stringify(initialTopics));
    return initialTopics;
  }
  return JSON.parse(topicsStr);
};

// 获取所有话题
export const getAllTopics = () => {
  return initTopics();
};

// 获取话题详情
export const getTopicById = (topicId) => {
  const topics = getAllTopics();
  return topics.find(topic => topic.id === parseInt(topicId));
};

// 创建新话题
export const createTopic = (topicData) => {
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const topics = getAllTopics();
  const newTopic = {
    id: Math.max(...topics.map(t => t.id), 0) + 1,
    name: topicData.name,
    description: topicData.description,
    creator: user.username,
    category: topicData.category,
    tags: topicData.tags || [],
    createTime: new Date().toISOString(),
    memberCount: 1,
    postCount: 0,
    isPublic: topicData.isPublic !== false,
    cover: topicData.cover || '/api/placeholder/400/200',
    rules: topicData.rules || []
  };

  topics.push(newTopic);
  localStorage.setItem('starrypt_topics', JSON.stringify(topics));

  return { success: true, topic: newTopic };
};

// 加入话题
export const joinTopic = (topicId) => {
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const topics = getAllTopics();
  const topicIndex = topics.findIndex(t => t.id === parseInt(topicId));

  if (topicIndex === -1) {
    return { success: false, message: '话题不存在' };
  }

  // 初始化话题成员数据
  const membersKey = `starrypt_topic_${topicId}_members`;
  const membersStr = localStorage.getItem(membersKey);
  let members = membersStr ? JSON.parse(membersStr) : [];

  // 检查用户是否已经加入
  const isAlreadyMember = members.some(member => member.username === user.username);
  if (isAlreadyMember) {
    return { success: false, message: '您已经是该话题的成员' };
  }

  // 添加用户到成员列表
  members.push({
    username: user.username,
    joinTime: new Date().toISOString(),
    role: 'member' // member, admin, creator
  });

  // 更新话题成员数量
  topics[topicIndex].memberCount = members.length;

  // 保存数据
  localStorage.setItem(membersKey, JSON.stringify(members));
  localStorage.setItem('starrypt_topics', JSON.stringify(topics));

  return { success: true, message: '成功加入话题' };
};

// 检查用户是否已加入话题
export const isUserJoinedTopic = (topicId) => {
  const user = getUser();
  if (!user) return false;

  const membersKey = `starrypt_topic_${topicId}_members`;
  const membersStr = localStorage.getItem(membersKey);
  const members = membersStr ? JSON.parse(membersStr) : [];

  return members.some(member => member.username === user.username);
};

// 获取话题成员列表
export const getTopicMembers = (topicId) => {
  const membersKey = `starrypt_topic_${topicId}_members`;
  const membersStr = localStorage.getItem(membersKey);
  return membersStr ? JSON.parse(membersStr) : [];
};

// 初始化话题内帖子数据
export const initTopicPosts = () => {
  const postsStr = localStorage.getItem('starrypt_topic_posts');
  if (!postsStr) {
    const initialPosts = [
      // 话题1的帖子（电影讨论圈）
      {
        id: 1,
        topicId: 1,
        title: '分享一些经典老电影4K修复版',
        content: '最近收集了一些经典老电影的4K修复版本，画质相当不错！\n\n包括：\n- 教父三部曲 4K修复版\n- 辛德勒的名单 4K版\n- 肖申克的救赎 4K版\n\n有需要的朋友可以私信我',
        type: 'resource',
        author: 'movie_collector',
        authorId: 4,
        createTime: '2023-12-01T10:00:00.000Z',
        likes: 25,
        comments: 8,
        viewCount: 156,
        isSticky: false,
        tags: ['4K', '经典电影', '修复版']
      },
      {
        id: 2,
        topicId: 1,
        title: '讨论：你们觉得哪部电影最值得反复观看？',
        content: '最近重看了《盗梦空间》，发现每次都能发现新的细节。大家有什么电影是百看不厌的吗？\n\n我的推荐：\n1. 盗梦空间 - 每次都有新发现\n2. 低俗小说 - 经典台词太多\n3. 肖申克的救赎 - 永远的经典',
        type: 'chat',
        author: 'cinema_lover',
        authorId: 8,
        createTime: '2023-12-02T14:30:00.000Z',
        likes: 18,
        comments: 24,
        viewCount: 89,
        isSticky: true,
        tags: ['讨论', '推荐', '经典']
      },
      {
        id: 3,
        topicId: 1,
        title: '求：奥本海默IMAX版本',
        content: '最近看了奥本海默的普通版，听说IMAX版效果更震撼。有人有IMAX版本的资源吗？\n\n愿意用15星币求购！',
        type: 'request',
        author: 'nolan_fan',
        authorId: 9,
        createTime: '2023-12-03T20:15:00.000Z',
        likes: 12,
        comments: 6,
        viewCount: 67,
        isSticky: false,
        tags: ['求种', 'IMAX', '诺兰'],
        bounty: 15
      },

      // 话题2的帖子（科幻迷聚集地）
      {
        id: 4,
        topicId: 2,
        title: '《流浪地球2》IMAX版本分享',
        content: '终于找到了高质量的流浪地球2 IMAX版本！\n\n- 格式：4K HDR IMAX\n- 大小：67.8GB\n- 音轨：杜比全景声\n\n特效场面真的太震撼了，推荐大家去看看！',
        type: 'resource',
        author: 'sci_fi_master',
        authorId: 5,
        createTime: '2023-12-05T09:20:00.000Z',
        likes: 42,
        comments: 18,
        viewCount: 234,
        isSticky: false,
        tags: ['IMAX', '科幻', '中国电影']
      },
      {
        id: 5,
        topicId: 2,
        title: '求《沙丘2》4K版本',
        content: '《沙丘2》已经上映了，有人有4K版本的资源吗？听说视觉效果非常棒！\n\n愿意用20星币求购高质量版本。',
        type: 'request',
        author: 'dune_fan',
        authorId: 10,
        createTime: '2023-12-06T16:45:00.000Z',
        likes: 28,
        comments: 12,
        viewCount: 156,
        isSticky: false,
        tags: ['求种', '科幻', '4K'],
        bounty: 20
      },
      {
        id: 6,
        topicId: 2,
        title: '科幻电影推荐清单（2023更新）',
        content: '整理了一份2023年值得观看的科幻电影清单：\n\n🔥 强烈推荐：\n- 沙丘2\n- 蜘蛛侠：纵横宇宙\n- 银河护卫队3\n\n📺 值得一看：\n- 变形金刚：超能勇士崛起\n- 闪电侠\n\n大家还有什么推荐的吗？',
        type: 'chat',
        author: 'future_vision',
        authorId: 11,
        createTime: '2023-12-07T11:30:00.000Z',
        likes: 35,
        comments: 29,
        viewCount: 187,
        isSticky: true,
        tags: ['推荐', '2023', '科幻']
      },

      // 话题3的帖子（学习资料分享）
      {
        id: 7,
        topicId: 3,
        title: '计算机科学经典教材合集',
        content: '整理了一些计算机科学的经典教材，包括：\n\n算法与数据结构：\n- 算法导论（第4版）\n- 数据结构与算法分析\n\n系统设计：\n- 深入理解计算机系统\n- 操作系统概念\n\n需要的同学可以私信我！',
        type: 'resource',
        author: 'cs_student',
        authorId: 12,
        createTime: '2023-12-04T13:15:00.000Z',
        likes: 67,
        comments: 23,
        viewCount: 345,
        isSticky: false,
        tags: ['计算机', '教材', '学习']
      },
      {
        id: 8,
        topicId: 3,
        title: '求机器学习相关课程视频',
        content: '最近在自学机器学习，有人有斯坦福CS229或者吴恩达机器学习课程的高清视频吗？\n\n愿意用12星币求购！',
        type: 'request',
        author: 'ml_learner',
        authorId: 13,
        createTime: '2023-12-08T19:20:00.000Z',
        likes: 15,
        comments: 8,
        viewCount: 92,
        isSticky: false,
        tags: ['求课程', '机器学习', '视频'],
        bounty: 12
      },

      // 话题4的帖子（音乐分享站）
      {
        id: 9,
        topicId: 4,
        title: 'Taylor Swift最新专辑高品质分享',
        content: 'Taylor Swift的最新专辑《Midnights》已经出了，分享一个无损版本：\n\n- 格式：FLAC 24bit/96kHz\n- 大小：1.2GB\n- 包含所有bonus tracks\n\n音质真的很棒，推荐给所有霉粉！',
        type: 'resource',
        author: 'swiftie_forever',
        authorId: 14,
        createTime: '2023-12-09T15:45:00.000Z',
        likes: 29,
        comments: 14,
        viewCount: 178,
        isSticky: false,
        tags: ['Taylor Swift', 'FLAC', '无损']
      },
      {
        id: 10,
        topicId: 4,
        title: '古典音乐入门推荐',
        content: '想给大家推荐一些古典音乐入门曲目：\n\n🎼 交响乐：\n- 贝多芬第九交响曲\n- 德沃夏克《新世界》\n\n🎹 钢琴：\n- 肖邦《夜曲》\n- 德彪西《月光》\n\n有兴趣的朋友可以从这些开始听！',
        type: 'chat',
        author: 'classical_music',
        authorId: 15,
        createTime: '2023-12-10T10:30:00.000Z',
        likes: 22,
        comments: 11,
        viewCount: 134,
        isSticky: false,
        tags: ['古典音乐', '入门', '推荐']
      }
    ];
    localStorage.setItem('starrypt_topic_posts', JSON.stringify(initialPosts));
    return initialPosts;
  }
  return JSON.parse(postsStr);
};

// 获取话题内所有帖子
export const getTopicPosts = (topicId) => {
  const posts = initTopicPosts();
  return posts.filter(post => post.topicId === parseInt(topicId));
};

// 在话题内发布帖子
export const createTopicPost = (topicId, postData) => {
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const posts = initTopicPosts();
  const newPost = {
    id: Math.max(...posts.map(p => p.id), 0) + 1,
    topicId: parseInt(topicId),
    title: postData.title,
    content: postData.content,
    type: postData.type || 'chat',
    author: user.username,
    createTime: new Date().toISOString(),
    likes: 0,
    comments: 0,
    viewCount: 0,
    isSticky: false,
    tags: postData.tags || [],
    bounty: postData.bounty || 0
  };

  posts.push(newPost);
  localStorage.setItem('starrypt_topic_posts', JSON.stringify(posts));

  // 更新话题的帖子数量
  const topics = getAllTopics();
  const topicIndex = topics.findIndex(t => t.id === parseInt(topicId));
  if (topicIndex !== -1) {
    topics[topicIndex].postCount += 1;
    localStorage.setItem('starrypt_topics', JSON.stringify(topics));
  }

  return { success: true, post: newPost };
};

// 获取帖子详情
export const getTopicPostById = (postId) => {
  const posts = initTopicPosts();
  return posts.find(post => post.id === parseInt(postId));
};

// 增加帖子查看次数
export const increasePostViewCount = (postId) => {
  const posts = initTopicPosts();
  const postIndex = posts.findIndex(post => post.id === parseInt(postId));

  if (postIndex !== -1) {
    posts[postIndex].viewCount = (posts[postIndex].viewCount || 0) + 1;
    localStorage.setItem('starrypt_topic_posts', JSON.stringify(posts));
    return posts[postIndex];
  }

  return null;
};

// 点赞话题帖子
export const likeTopicPost = (postId) => {
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const posts = initTopicPosts();
  const postIndex = posts.findIndex(post => post.id === parseInt(postId));

  if (postIndex === -1) {
    return { success: false, message: '帖子不存在' };
  }

  // 检查用户是否已经点赞过
  const likesKey = `starrypt_post_${postId}_likes`;
  const likesStr = localStorage.getItem(likesKey);
  let likes = likesStr ? JSON.parse(likesStr) : [];

  const hasLiked = likes.some(like => like.username === user.username);
  if (hasLiked) {
    return { success: false, message: '您已经点赞过了' };
  }

  // 添加点赞记录
  likes.push({
    username: user.username,
    likeTime: new Date().toISOString()
  });

  // 更新帖子点赞数
  posts[postIndex].likes = likes.length;

  // 保存数据
  localStorage.setItem(likesKey, JSON.stringify(likes));
  localStorage.setItem('starrypt_topic_posts', JSON.stringify(posts));

  return { success: true, message: '点赞成功', likes: likes.length };
};

// 初始化分区数据
export const initCategories = () => {
  const categoriesStr = localStorage.getItem('starrypt_categories');
  if (!categoriesStr) {
    const initialCategories = [
      {
        id: 1,
        name: '电影',
        description: '各类电影资源',
        icon: 'film',
        color: '#1890ff',
        resourceCount: 1250
      },
      {
        id: 2,
        name: '电视剧',
        description: '电视剧集资源',
        icon: 'tv',
        color: '#52c41a',
        resourceCount: 856
      },
      {
        id: 3,
        name: '纪录片',
        description: '纪录片资源',
        icon: 'camera',
        color: '#722ed1',
        resourceCount: 234
      },
      {
        id: 4,
        name: '动漫',
        description: '动画与漫画资源',
        icon: 'star',
        color: '#eb2f96',
        resourceCount: 567
      },
      {
        id: 5,
        name: '音乐',
        description: '音乐专辑资源',
        icon: 'sound',
        color: '#fa8c16',
        resourceCount: 389
      },
      {
        id: 6,
        name: '图书',
        description: '电子书籍资源',
        icon: 'book',
        color: '#13c2c2',
        resourceCount: 445
      },
      {
        id: 7,
        name: '软件',
        description: '软件与应用资源',
        icon: 'laptop',
        color: '#2f54eb',
        resourceCount: 156
      },
      {
        id: 8,
        name: '游戏',
        description: '游戏资源',
        icon: 'gamepad',
        color: '#f5222d',
        resourceCount: 234
      }
    ];
    localStorage.setItem('starrypt_categories', JSON.stringify(initialCategories));
    return initialCategories;
  }
  return JSON.parse(categoriesStr);
};

// 获取所有分区
export const getAllCategories = () => {
  return initCategories();
};

// 初始化全球广播数据
export const initBroadcasts = () => {
  const broadcastsStr = localStorage.getItem('starrypt_broadcasts');
  if (!broadcastsStr) {
    const initialBroadcasts = [
      {
        id: 1,
        type: 'resource', // resource, request
        title: '【4K HDR】阿凡达：水之道 完整版',
        content: '最新的阿凡达2，4K HDR版本，音画质量极佳！',
        author: 'avatar_fan',
        authorId: 7,
        createTime: '2023-12-10T09:30:00.000Z',
        likes: 45,
        downloads: 23,
        category: '电影',
        tags: ['4K', 'HDR', '科幻'],
        resourceLink: 'magnet:?xt=urn:btih:...',
        size: '45.6 GB',
        starCoinCost: 2
      },
      {
        id: 2,
        type: 'request',
        title: '求《三体》电视剧完整版',
        content: '求最新的《三体》电视剧，有字幕版本最好',
        author: 'sci_fi_lover',
        authorId: 8,
        createTime: '2023-12-10T14:20:00.000Z',
        likes: 12,
        bounty: 5,
        category: '电视剧',
        tags: ['科幻', '国产剧'],
        urgency: 'high', // low, normal, high
        viewCount: 67
      }
    ];
    localStorage.setItem('starrypt_broadcasts', JSON.stringify(initialBroadcasts));
    return initialBroadcasts;
  }
  return JSON.parse(broadcastsStr);
};

// 获取所有广播
export const getAllBroadcasts = () => {
  return initBroadcasts();
};

// 发布广播
export const createBroadcast = (broadcastData) => {
  const user = getUser();
  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  // 检查星币是否足够(如果是求种)
  if (broadcastData.type === 'request' && broadcastData.bounty > 0) {
    const userPoints = getUserPoints(user.username);
    if (userPoints.starCoins < broadcastData.bounty) {
      return { success: false, message: '星币不足' };
    }

    // 扣除星币
    updateUserPoints(user.username, {
      starCoins: userPoints.starCoins - broadcastData.bounty
    });
  }

  const broadcasts = getAllBroadcasts();
  const newBroadcast = {
    id: Math.max(...broadcasts.map(b => b.id), 0) + 1,
    type: broadcastData.type,
    title: broadcastData.title,
    content: broadcastData.content,
    author: user.username,
    createTime: new Date().toISOString(),
    likes: 0,
    downloads: 0,
    category: broadcastData.category,
    tags: broadcastData.tags || [],
    resourceLink: broadcastData.resourceLink || '',
    size: broadcastData.size || '',
    starCoinCost: broadcastData.starCoinCost || 0,
    bounty: broadcastData.bounty || 0,
    urgency: broadcastData.urgency || 'normal',
    viewCount: 0
  };

  broadcasts.unshift(newBroadcast); // 添加到开头
  localStorage.setItem('starrypt_broadcasts', JSON.stringify(broadcasts));

  return { success: true, broadcast: newBroadcast };
};

// =========== 社区相关操作 ===========

// 初始化论坛主题数据
export const initForumTopics = () => {
  const topicsStr = localStorage.getItem('starrypt_forum_topics');
  if (!topicsStr) {
    const initialTopics = [
      {
        id: 1,
        title: '欢迎来到星域PT站！新手必读指南',
        content: '欢迎各位新老用户来到星域PT站！这里是我们的官方论坛，大家可以在这里交流分享、讨论技术问题、发布资源信息等。\n\n新手用户请注意：\n1. 请保持良好的分享率\n2. 遵守站点规则\n3. 积极参与社区讨论\n\n有任何问题欢迎在论坛提问！',
        author: 'admin',
        authorId: 1,
        category: '公告',
        tags: ['新手', '指南', '规则'],
        createTime: '2023-01-01T00:00:00.000Z',
        updateTime: '2023-01-01T00:00:00.000Z',
        views: 1250,
        replies: 45,
        likes: 89,
        isSticky: true,
        isLocked: false,
        lastReplyTime: '2023-12-10T15:30:00.000Z',
        lastReplyAuthor: 'user123'
      },
      {
        id: 2,
        title: '分享一些优质4K电影资源',
        content: '最近收集了一些高质量的4K电影资源，包括：\n\n1. 星际穿越 4K蓝光原盘\n2. 流浪地球2 4K HDR\n3. 阿凡达：水之道 4K\n4. 沙丘 4K IMAX版\n\n所有资源都经过严格筛选，画质音质都是顶级的。有需要的朋友可以关注一下！',
        author: 'movie_lover',
        authorId: 2,
        category: '资源分享',
        tags: ['4K', '电影', '蓝光'],
        createTime: '2023-11-15T10:20:00.000Z',
        updateTime: '2023-11-15T10:20:00.000Z',
        views: 856,
        replies: 23,
        likes: 67,
        isSticky: false,
        isLocked: false,
        lastReplyTime: '2023-12-09T20:15:00.000Z',
        lastReplyAuthor: 'cinema_fan'
      },
      {
        id: 3,
        title: 'PT站下载速度优化技巧分享',
        content: '作为一个老用户，分享一些提高PT站下载速度的技巧：\n\n1. 选择合适的BT客户端（推荐qBittorrent、Transmission）\n2. 合理设置上传下载限速\n3. 选择做种人数多的资源\n4. 避开高峰时段下载\n5. 保持良好的分享率\n\n希望对新手朋友有帮助！',
        author: 'tech_expert',
        authorId: 3,
        category: '技术讨论',
        tags: ['技巧', '下载', '优化'],
        createTime: '2023-11-20T14:45:00.000Z',
        updateTime: '2023-11-20T14:45:00.000Z',
        views: 642,
        replies: 18,
        likes: 45,
        isSticky: false,
        isLocked: false,
        lastReplyTime: '2023-12-08T11:30:00.000Z',
        lastReplyAuthor: 'newbie_user'
      },
      {
        id: 4,
        title: '求助：如何提高分享率？',
        content: '各位大佬好，我是新注册的用户，目前分享率比较低，想请教一下如何快速提高分享率？\n\n我现在的情况：\n- 下载了几个热门资源\n- 24小时挂机做种\n- 但是上传速度很慢\n\n有什么好的建议吗？谢谢！',
        author: 'newbie_123',
        authorId: 4,
        category: '求助问答',
        tags: ['求助', '分享率', '新手'],
        createTime: '2023-12-05T09:15:00.000Z',
        updateTime: '2023-12-05T09:15:00.000Z',
        views: 234,
        replies: 12,
        likes: 8,
        isSticky: false,
        isLocked: false,
        lastReplyTime: '2023-12-07T16:20:00.000Z',
        lastReplyAuthor: 'helpful_user'
      },
      {
        id: 5,
        title: '2023年度最佳科幻电影推荐',
        content: '年底了，来总结一下2023年的优质科幻电影：\n\n1. 流浪地球2 - 国产科幻的新高度\n2. 银河护卫队3 - 漫威宇宙的完美收官\n3. 变形金刚：超能勇士崛起 - 怀旧与创新的结合\n4. 闪电侠 - DC多元宇宙的探索\n\n大家还有什么推荐的吗？',
        author: 'sci_fi_fan',
        authorId: 5,
        category: '影视讨论',
        tags: ['科幻', '电影', '推荐', '2023'],
        createTime: '2023-12-01T20:00:00.000Z',
        updateTime: '2023-12-01T20:00:00.000Z',
        views: 445,
        replies: 28,
        likes: 52,
        isSticky: false,
        isLocked: false,
        lastReplyTime: '2023-12-10T12:45:00.000Z',
        lastReplyAuthor: 'movie_critic'
      }
    ];

    localStorage.setItem('starrypt_forum_topics', JSON.stringify(initialTopics));
    return initialTopics;
  }

  return JSON.parse(topicsStr);
};

// 初始化论坛回复数据
export const initForumReplies = () => {
  const repliesStr = localStorage.getItem('starrypt_forum_replies');
  if (!repliesStr) {
    const initialReplies = [
      {
        id: 1,
        topicId: 1,
        content: '感谢管理员的详细指南！作为新用户受益匪浅。',
        author: 'user123',
        authorId: 6,
        createTime: '2023-01-02T10:30:00.000Z',
        likes: 12,
        floor: 1
      },
      {
        id: 2,
        topicId: 1,
        content: '规则很清楚，希望大家都能遵守，共同维护好站点环境。',
        author: 'community_lover',
        authorId: 7,
        createTime: '2023-01-03T15:20:00.000Z',
        likes: 8,
        floor: 2
      },
      {
        id: 3,
        topicId: 2,
        content: '太棒了！正好在找4K资源，楼主辛苦了！',
        author: 'cinema_fan',
        authorId: 8,
        createTime: '2023-11-16T09:45:00.000Z',
        likes: 15,
        floor: 1
      },
      {
        id: 4,
        topicId: 2,
        content: '星际穿越4K版本画质真的震撼，强烈推荐！',
        author: 'quality_seeker',
        authorId: 9,
        createTime: '2023-11-17T14:30:00.000Z',
        likes: 10,
        floor: 2
      },
      {
        id: 5,
        topicId: 3,
        content: '非常实用的技巧！按照楼主的方法，下载速度确实提升了不少。',
        author: 'speed_user',
        authorId: 10,
        createTime: '2023-11-21T11:15:00.000Z',
        likes: 18,
        floor: 1
      },
      {
        id: 6,
        topicId: 4,
        content: '建议多下载一些冷门但优质的资源，竞争小，上传机会多。',
        author: 'helpful_user',
        authorId: 11,
        createTime: '2023-12-06T13:40:00.000Z',
        likes: 6,
        floor: 1
      },
      {
        id: 7,
        topicId: 4,
        content: '还有就是要保持长期做种，即使速度慢也要坚持。',
        author: 'patient_seeder',
        authorId: 12,
        createTime: '2023-12-07T16:20:00.000Z',
        likes: 4,
        floor: 2
      },
      {
        id: 8,
        topicId: 5,
        content: '流浪地球2确实不错！特效和剧情都很棒。',
        author: 'movie_critic',
        authorId: 13,
        createTime: '2023-12-02T21:30:00.000Z',
        likes: 9,
        floor: 1
      }
    ];

    localStorage.setItem('starrypt_forum_replies', JSON.stringify(initialReplies));
    return initialReplies;
  }

  return JSON.parse(repliesStr);
};

// 初始化公告数据
export const initAnnouncements = () => {
  const announcementsStr = localStorage.getItem('starrypt_announcements');
  if (!announcementsStr) {
    const initialAnnouncements = [
      {
        id: 1,
        title: '星域PT站正式上线公告',
        content: '亲爱的用户们：\n\n经过长时间的筹备和测试，星域PT站今日正式上线！\n\n我们致力于为大家提供高质量的资源分享平台，主要特色包括：\n\n1. 严格的资源质量控制\n2. 完善的用户积分体系\n3. 活跃的社区讨论环境\n4. 24/7技术支持服务\n\n欢迎大家积极参与，共同建设我们的社区！\n\n星域PT站管理团队\n2023年1月1日',
        author: 'admin',
        authorId: 1,
        createTime: '2023-01-01T00:00:00.000Z',
        updateTime: '2023-01-01T00:00:00.000Z',
        views: 2580,
        isImportant: true,
        category: '重要公告'
      },
      {
        id: 2,
        title: '关于提高分享率要求的通知',
        content: '各位用户：\n\n为了维护站点的健康发展，现对用户分享率要求进行调整：\n\n1. 新用户注册后30天内，分享率需达到0.5以上\n2. 注册满30天的用户，分享率需保持在0.8以上\n3. 分享率长期低于要求的用户将被限制下载\n\n建议大家：\n- 积极参与做种\n- 上传优质资源\n- 保持长期在线\n\n感谢大家的理解与配合！\n\n管理团队\n2023年6月15日',
        author: 'admin',
        authorId: 1,
        createTime: '2023-06-15T10:00:00.000Z',
        updateTime: '2023-06-15T10:00:00.000Z',
        views: 1890,
        isImportant: true,
        category: '规则更新'
      },
      {
        id: 3,
        title: '服务器维护通知',
        content: '各位用户：\n\n为了提升服务质量，我们将于本周末进行服务器维护升级：\n\n维护时间：2023年12月16日 02:00 - 06:00\n影响范围：网站可能短暂无法访问\n维护内容：\n- 服务器硬件升级\n- 系统安全更新\n- 性能优化\n\n维护期间给大家带来的不便，敬请谅解！\n\n技术团队\n2023年12月10日',
        author: 'tech_admin',
        authorId: 14,
        createTime: '2023-12-10T16:00:00.000Z',
        updateTime: '2023-12-10T16:00:00.000Z',
        views: 567,
        isImportant: false,
        category: '维护通知'
      },
      {
        id: 4,
        title: '新增资源分类说明',
        content: '各位用户：\n\n应大家要求，我们新增了以下资源分类：\n\n1. 纪录片 - 包含各类优质纪录片资源\n2. 动漫 - 日本动画、国产动画等\n3. 音乐 - 无损音乐、演唱会等\n4. 软件 - 正版软件、开源工具等\n5. 电子书 - 技术书籍、文学作品等\n\n上传资源时请选择正确的分类，便于其他用户查找。\n\n感谢大家的支持！\n\n管理团队\n2023年11月20日',
        author: 'admin',
        authorId: 1,
        createTime: '2023-11-20T14:30:00.000Z',
        updateTime: '2023-11-20T14:30:00.000Z',
        views: 823,
        isImportant: false,
        category: '功能更新'
      },
      {
        id: 5,
        title: '年终活动预告',
        content: '各位用户：\n\n2023年即将结束，为了感谢大家一年来的支持，我们将举办年终感谢活动：\n\n活动时间：2023年12月25日 - 2024年1月5日\n活动内容：\n1. 上传奖励翻倍\n2. 优质资源评选\n3. 积分兑换礼品\n4. 社区互动抽奖\n\n具体活动规则将于近期公布，敬请期待！\n\n祝大家新年快乐！\n\n星域PT站全体成员\n2023年12月8日',
        author: 'admin',
        authorId: 1,
        createTime: '2023-12-08T18:00:00.000Z',
        updateTime: '2023-12-08T18:00:00.000Z',
        views: 1245,
        isImportant: true,
        category: '活动公告'
      }
    ];

    localStorage.setItem('starrypt_announcements', JSON.stringify(initialAnnouncements));
    return initialAnnouncements;
  }

  return JSON.parse(announcementsStr);
};

// 获取所有论坛主题
export const getAllForumTopics = () => {
  let topics = localStorage.getItem('starrypt_forum_topics');
  if (!topics) {
    topics = initForumTopics();
  } else {
    topics = JSON.parse(topics);
  }
  return topics;
};

// 根据ID获取论坛主题
export const getForumTopicById = (id) => {
  const topics = getAllForumTopics();
  return topics.find(topic => topic.id === parseInt(id, 10)) || null;
};

// 获取主题的回复
export const getTopicReplies = (topicId) => {
  let replies = localStorage.getItem('starrypt_forum_replies');
  if (!replies) {
    replies = initForumReplies();
  } else {
    replies = JSON.parse(replies);
  }
  return replies.filter(reply => reply.topicId === parseInt(topicId, 10));
};

// 添加新主题
export const addForumTopic = (topicData) => {
  const topics = getAllForumTopics();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const newTopic = {
    id: Date.now(),
    ...topicData,
    author: user.username,
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
    views: 0,
    replies: 0,
    likes: 0,
    isSticky: false,
    isLocked: false,
    lastReplyTime: new Date().toISOString(),
    lastReplyAuthor: user.username
  };

  topics.push(newTopic);
  localStorage.setItem('starrypt_forum_topics', JSON.stringify(topics));

  return { success: true, topic: newTopic };
};

// 添加回复
export const addTopicReply = (topicId, content) => {
  const topics = getAllForumTopics();
  const replies = JSON.parse(localStorage.getItem('starrypt_forum_replies')) || initForumReplies();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const topicIndex = topics.findIndex(t => t.id === parseInt(topicId, 10));
  if (topicIndex === -1) {
    return { success: false, message: '主题不存在' };
  }

  // 计算楼层号
  const topicReplies = replies.filter(r => r.topicId === parseInt(topicId, 10));
  const floor = topicReplies.length + 1;

  const newReply = {
    id: Date.now(),
    topicId: parseInt(topicId, 10),
    content,
    author: user.username,
    createTime: new Date().toISOString(),
    likes: 0,
    floor
  };

  replies.push(newReply);
  localStorage.setItem('starrypt_forum_replies', JSON.stringify(replies));

  // 更新主题的回复数和最后回复信息
  topics[topicIndex].replies += 1;
  topics[topicIndex].lastReplyTime = new Date().toISOString();
  topics[topicIndex].lastReplyAuthor = user.username;
  topics[topicIndex].updateTime = new Date().toISOString();
  localStorage.setItem('starrypt_forum_topics', JSON.stringify(topics));

  return { success: true, reply: newReply };
};

// 点赞主题
export const likeForumTopic = (topicId) => {
  const topics = getAllForumTopics();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const topicIndex = topics.findIndex(t => t.id === parseInt(topicId, 10));
  if (topicIndex === -1) {
    return { success: false, message: '主题不存在' };
  }

  topics[topicIndex].likes += 1;
  localStorage.setItem('starrypt_forum_topics', JSON.stringify(topics));

  return { success: true, likes: topics[topicIndex].likes };
};

// 点赞回复
export const likeTopicReply = (replyId) => {
  const replies = JSON.parse(localStorage.getItem('starrypt_forum_replies')) || initForumReplies();
  const user = getUser();

  if (!user) {
    return { success: false, message: '用户未登录' };
  }

  const replyIndex = replies.findIndex(r => r.id === parseInt(replyId, 10));
  if (replyIndex === -1) {
    return { success: false, message: '回复不存在' };
  }

  replies[replyIndex].likes += 1;
  localStorage.setItem('starrypt_forum_replies', JSON.stringify(replies));

  return { success: true, likes: replies[replyIndex].likes };
};

// 增加主题浏览量
export const increaseTopicViews = (topicId) => {
  const topics = getAllForumTopics();
  const topicIndex = topics.findIndex(t => t.id === parseInt(topicId, 10));

  if (topicIndex !== -1) {
    topics[topicIndex].views += 1;
    localStorage.setItem('starrypt_forum_topics', JSON.stringify(topics));
    return topics[topicIndex].views;
  }

  return 0;
};

// 获取所有公告
export const getAllAnnouncements = () => {
  let announcements = localStorage.getItem('starrypt_announcements');
  if (!announcements) {
    announcements = initAnnouncements();
  } else {
    announcements = JSON.parse(announcements);
  }
  return announcements;
};

// 根据ID获取公告
export const getAnnouncementById = (id) => {
  const announcements = getAllAnnouncements();
  return announcements.find(announcement => announcement.id === parseInt(id, 10)) || null;
};

// 增加公告浏览量
export const increaseAnnouncementViews = (announcementId) => {
  const announcements = getAllAnnouncements();
  const announcementIndex = announcements.findIndex(a => a.id === parseInt(announcementId, 10));

  if (announcementIndex !== -1) {
    announcements[announcementIndex].views += 1;
    localStorage.setItem('starrypt_announcements', JSON.stringify(announcements));
    return announcements[announcementIndex].views;
  }

  return 0;
};

// 搜索论坛主题
export const searchForumTopics = (query) => {
  const topics = getAllForumTopics();
  if (!query) return topics;

  const lowerQuery = query.toLowerCase();
  return topics.filter(topic =>
    topic.title.toLowerCase().includes(lowerQuery) ||
    topic.content.toLowerCase().includes(lowerQuery) ||
    topic.tags.some(tag => tag.toLowerCase().includes(lowerQuery)) ||
    topic.author.toLowerCase().includes(lowerQuery)
  );
};

// 根据分类获取论坛主题
export const getForumTopicsByCategory = (category) => {
  const topics = getAllForumTopics();
  return category ? topics.filter(topic => topic.category === category) : topics;
}; 